package com.gf.pokemon.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.gf.pokemon.dto.VoteDto;
import com.gf.pokemon.dto.VoteUserDetailDto;
import com.gf.pokemon.dto.VoteUserDto;
import com.gf.pokemon.platform.exception.PokeErrorCode;
import com.gf.pokemon.platform.exception.PokeException;
import com.gf.pokemon.platform.result.PokeResult;
import com.gf.pokemon.remote.oa.OaService;
import com.gf.pokemon.service.VoteService;
import com.gf.pokemon.service.VoteUserService;
import com.gf.pokemon.util.ConvertUtils;
import com.gf.pokemon.util.page.Page;
import com.gf.pokemon.util.page.PagedList;

import javax.annotation.Resource;

@Controller
@RequestMapping("/")
public class BaseController {
	
	private Logger logger = Logger.getLogger(BaseController.class);
	
	private final String SUCCESS = "ok";
	
	private final String tableDataName = "aaData";
	
	private final String tableDataTotal = "iTotalRecords";

	private final String tableDataTotalDisplay = "iTotalDisplayRecords";
	
	private final String tableDataStart = "iDisplayStart";
	
	private final String tableDataPageSize = "iDisplayLength";
	
	private final String tableSearch = "sSearch";
	
	private final String tableDataKey = "name";
	
	private final String tableDataValue = "value";
	
	@Resource
	private VoteService voteService;
	
	@Resource
	private VoteUserService voteUserService;
	
	@Resource
	private OaService oaService;

	@RequestMapping("/")
	public ModelAndView index(){
		return new ModelAndView("login");
	}

	@RequestMapping("/vote/statics")
	public ModelAndView statics() throws Exception{
		ModelAndView mv = new ModelAndView("saticsIndex");
		return mv;
	}

	@RequestMapping("/vote/create")
	public ModelAndView create() throws Exception{
		ModelAndView mv = new ModelAndView("create-option");
		return mv;
	}
	
	@RequestMapping("/vote/show")
	public ModelAndView showVote(Integer voteId) throws Exception{
		if(voteId==null){
			throw new PokeException(PokeErrorCode.INVALID_PARAM);
		}
		ModelAndView mv = new ModelAndView("saveUserVote");
		return mv;
	}
	
	@RequestMapping("/vote/showUpate")
	public ModelAndView showVoteUserUpate() throws Exception{
		ModelAndView mv = new ModelAndView("updateUserVote");
		return mv;
	}
	
	@RequestMapping("/vote/showVoteStatics")
	public ModelAndView showVoteStatics(Integer voteId) throws Exception{
		if(voteId==null){
			throw new PokeException(PokeErrorCode.INVALID_PARAM);
		}
		ModelAndView mv = new ModelAndView("vote");
		return mv;
	}
	
	@RequestMapping("/vote/save")
	@ResponseBody
	public String saveVote(@RequestBody String jsonVote) throws Exception{
		if(jsonVote==null){
			throw new PokeException(PokeErrorCode.INVALID_PARAM);
		}
		VoteDto voteDto = ConvertUtils.convertJsonToVote(jsonVote);
		voteService.saveVote(voteDto);
		return PokeResult.getPokeResultSuccess(SUCCESS);
	}
	
	/**
	 * 保存用户投票信息
	 * @param jsonVoteUser
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/vote/saveUser")
	@ResponseBody
	public String saveVoteUser(@RequestBody String jsonVoteUser) throws Exception{
		if(jsonVoteUser==null){
			throw new PokeException(PokeErrorCode.INVALID_PARAM);
		}
		VoteUserDto voteUser = ConvertUtils.convertJsonToVoteUser(jsonVoteUser);
		voteUserService.saveVoteUser(voteUser);
		return PokeResult.getPokeResultSuccess(SUCCESS);
	}

	/**
	 * 更新用户投票信息
	 * @param jsonVoteUser
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/vote/updateUser")
	@ResponseBody
	public String updateVoteUser(@RequestBody String jsonVoteUser) throws Exception{
		if(jsonVoteUser==null){
			throw new PokeException(PokeErrorCode.INVALID_PARAM);
		}
		VoteUserDto voteUser = ConvertUtils.convertJsonToVoteUser(jsonVoteUser);
		voteUserService.updateVoteUser(voteUser);
		return PokeResult.getPokeResultSuccess(SUCCESS);
	}
	
	/**
	 * 获取单个用户投票信息
	 * @param jsonVoteUser
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/vote/getUser")
	@ResponseBody
	public String getUser(Integer voteId, Integer voteUserId) throws Exception{
		if(voteId==null || voteUserId==null){
			throw new PokeException(PokeErrorCode.INVALID_PARAM,"voteId 或 voteUserId为空");
		}
		VoteUserDto voteUser = voteUserService.getVoteUser(voteId, voteUserId);
		return PokeResult.getPokeResultSuccess(voteUser);
	}
	
	/**
	 * 获取投票主题列表
	 * @param aoData
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/vote/getVoteList")
	@ResponseBody
	public String getVoteList(String aoData) throws Exception{
		Page page = new Page();
		VoteDto dto = new VoteDto();
		AoDataPage aoDataPage = parseAoData(aoData);
		page.setOffset(aoDataPage.offset);
		page.setPageSize(aoDataPage.pageSize);
		dto.setTitle(aoDataPage.search);
		PagedList<VoteDto> votePage = voteService.getVotePage(dto, page);
		return PokeResult.getPokeResultSuccess(constructPageResult(votePage));
	}
	
	/**
	 * 获取单个投票主题信息
	 * @param voteId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/vote/get")
	@ResponseBody
	public String getVote(Integer voteId) throws Exception{
		if(voteId==null){
			throw new PokeException(PokeErrorCode.INVALID_PARAM);
		}
		VoteDto dto = voteService.getVoteById(voteId);
		return PokeResult.getPokeResultSuccess(dto);
	}
	
	/**
	 * 获取投票主题统计信息
	 * @param voteId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/vote/getUserVoteStatics")
	@ResponseBody	
	public String getUserVoteStatics(Integer voteId) throws Exception{
		if(voteId==null){
			throw new PokeException(PokeErrorCode.INVALID_PARAM);
		}
		return PokeResult.getPokeResultSuccess(voteUserService.getStaticsByVoteId(voteId));
	}

	/**
	 * 获取投票详情，标题头
	 * @param voteId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/vote/getUserDetailTitle")
	@ResponseBody	
	public String getUserDetailTitle(Integer voteId) throws Exception{
		if(voteId==null){
			throw new PokeException(PokeErrorCode.INVALID_PARAM);
		}
		return PokeResult.getPokeResultSuccess(voteUserService.getVoteDetailTitle(voteId));
	}
	
	/**
	 * 获取投票详情信息
	 * @param voteId
	 * @param aoData
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/vote/getUserDetail")
	@ResponseBody	
	public String getUserDetail(Integer voteId,String aoData) throws Exception{
		if(voteId==null || aoData==null){
			throw new PokeException(PokeErrorCode.INVALID_PARAM);
		}
		AoDataPage aoDataPage = parseAoData(aoData);
		Page page = new Page();
		page.setOffset(aoDataPage.offset);
		page.setPageSize(aoDataPage.pageSize);
		PagedList<VoteUserDetailDto> voteDetailByPage = voteUserService.getVoteDetailByPage(voteId, page);
		return PokeResult.getPokeResultSuccess(constructPageResult(voteDetailByPage));
	}
	
	/**
	 * 投票详情下载excel
	 * @param voteId
	 * @return
	 * @throws PokeException
	 */
	@RequestMapping(value="/vote/getUserDetailExcel")
	public ResponseEntity<byte[]> getUserDetailExcel(Integer voteId) throws PokeException {
		if(voteId==null){
			throw new PokeException(PokeErrorCode.INVALID_PARAM,"voteId为空");
		}
		byte[] data = voteUserService.getVoteDetailByPageExcel(voteId);
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		headers.setContentDispositionFormData("attachment", "userVoteDetail.xls");
		return new ResponseEntity<byte[]>(data,headers, HttpStatus.CREATED);
	}
	
	@RequestMapping(value="/vote/pushOA")
	@ResponseBody
	public String pushOA(){
		oaService.pushOA("test", "test", "我的测试", "lihl", Arrays.asList("lihl"), "1", "/vote/show?voteId=22");
		return PokeResult.getPokeResultSuccess(SUCCESS);
	}

	
	/**
	 * 将PagedList构造成DataTable的返回格式
	 * @param pageList
	 * @return
	 */
	private Map<String,Object> constructPageResult(PagedList pageList){
		Map<String,Object> result = new HashMap<String,Object>();
		result.put(tableDataTotal, pageList.getPage().getTotal());
		result.put(tableDataTotalDisplay, pageList.getPage().getTotal());
		result.put(tableDataName, pageList.getList());
		return result;
	}
	
	/**
	 * 解析dataTable的输入
	 * @param aoData
	 * @return
	 */
	private AoDataPage parseAoData(String aoData){
		AoDataPage page = new AoDataPage();
		JSONArray jList = JSONArray.fromObject(aoData);
		for(int i=0;i<jList.size();i++){
			JSONObject data = (JSONObject)jList.get(i);
			if(tableDataStart.equals(data.getString(tableDataKey))){
				page.offset = data.getInt(tableDataValue);
			}
			if(tableDataPageSize.equals(data.getString(tableDataKey))){
				page.pageSize = data.getInt(tableDataValue);
			}
			if(tableSearch.equals(data.getString(tableDataKey))){
				if(StringUtils.isNotBlank(data.getString(tableDataValue))){
					page.search = data.getString(tableDataValue);
				}				
			}
		}
		return page;
	}
	
	public VoteUserService getVoteUserService() {
		return voteUserService;
	}

	public void setVoteUserService(VoteUserService voteUserService) {
		this.voteUserService = voteUserService;
	}
	
	class AoDataPage{
		Integer offset;
		Integer pageSize;
		String search;
	}
}
